package com.cloud.pet.ops.handler;

import com.cloud.pet.ops.enums.PortalResultEnum;
import com.cloud.commons.Result;
import com.cloud.commons.exception.BusinessException;
import com.cloud.commons.exception.ParamsValidateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;

/**
 * description:全局异常处理类
 * Author	Date	Changes
 * tc  2019年1月28日 Created
 */
@ControllerAdvice
@ResponseBody
@Order(1001)
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result<?> exceptionHandler(HttpServletRequest request, Exception e) {
        Result<?> result = new Result<>();
        //绑定异常是需要明确提示给用户的
        if (e instanceof BusinessException) {
            result.setMessage(e.getMessage());
            result.setCode(((BusinessException) e).getCode());
        } else if (e instanceof NoSuchAlgorithmException) {
            log.error("create salt or password is error.", e);
            result.setMessage(e.getMessage());
            result.setCode(((BusinessException) e).getCode());
        } else if (e instanceof ParamsValidateException) {
            result.setMessage(e.getMessage());
            result.setCode(((ParamsValidateException) e).getCode());
        } else {
            log.error("全局异常", e);
            return Result.build(PortalResultEnum.SYSTEM_EXCEPTION.getCode(), PortalResultEnum.SYSTEM_EXCEPTION.getMessage());
        }
        return result;
    }
}
